package com.sky.service.user.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealMapper;
import com.sky.mapper.user.ShoppingCartMapper;
import com.sky.pojo.ShoppingCart;
import com.sky.service.user.ShoppingCartService;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.beancontext.BeanContext;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description ShoppingCartServiceImpl
 * @Author lyh
 * @Date 2024-10-07
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    /**
     * 添加购物车
     * @param dto
     * @return
     */
    @Override
    public void addCart(ShoppingCartDTO dto) {
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(dto,shoppingCart);
        shoppingCart.setUserId(BaseContext.getCurrentId());
        //查找数据库判断是否存在当前菜品
      List<ShoppingCart> shoppingCartList=  shoppingCartMapper.queryByContional(shoppingCart);
      if(shoppingCartList!=null && shoppingCartList.size()>0){
          //购物车已存在，数量加一
          shoppingCartMapper.addCartNumberById(shoppingCartList.get(0).getId());
      }else{
          //不存在
          //补充属性
          shoppingCart.setNumber(1);
          shoppingCart.setCreateTime(LocalDateTime.now());
          if(shoppingCart.getDishId()!=null){
              DishVO dishVO = dishMapper.getById(shoppingCart.getDishId());
              shoppingCart.setImage(dishVO.getImage());
              shoppingCart.setName(dishVO.getName());
              shoppingCart.setAmount(dishVO.getPrice());
              //添加到数据库
              shoppingCartMapper.addCart(shoppingCart);
          }else if(shoppingCart.getSetmealId()!=null){
              SetmealVO setmealVO = setmealMapper.getById(shoppingCart.getSetmealId());
              shoppingCart.setImage(setmealVO.getImage());
              shoppingCart.setName(setmealVO.getName());
              shoppingCart.setAmount(setmealVO.getPrice());
              //添加到数据库
              shoppingCartMapper.addCart(shoppingCart);
          }
      }

    }

    /**
     * 根据当前用户获取购物车
     * @return
     */
    @Override
    public List<ShoppingCart> getShoppingCartListByUserId() {
        Long userId=BaseContext.getCurrentId();
        List<ShoppingCart>list= shoppingCartMapper.getShoppingCartListByUserId(userId);
        return list;
    }

    /**
     * 根据当前用户清空购物车
     */
    @Override
    public void cleanCartByUserId() {
        Long userId=BaseContext.getCurrentId();
        shoppingCartMapper.cleanCartByUserId(userId);
    }
}
